package com.zhuiYun.project.api.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.zhuiYun.project.api.alipay.entity.AlipayEntity;
import com.zhuiYun.project.api.alipay.service.AlipayService;
import com.zhuiYun.project.api.commoditydetail.entity.Commodity;
import com.zhuiYun.project.api.commoditydetail.mapper.CommodityMapper;
import com.zhuiYun.project.api.commodityorder.entity.CommodityOrder;
import com.zhuiYun.project.api.commodityorder.mapper.CommodityOrderMapper;
import com.zhuiYun.project.api.handworkdiy.entity.HandworkDiy;
import com.zhuiYun.project.api.handworkdiy.mapper.HandworkDiyMapper;
import com.zhuiYun.project.api.handworkdiyorder.entity.HandworkDiyOrder;
import com.zhuiYun.project.api.handworkdiyorder.mapper.HandworkDiyOrderMapper;
import com.zhuiYun.project.api.order.entity.*;
import com.zhuiYun.project.api.order.mapper.OrderMapper;
import com.zhuiYun.project.api.order.mapper.OrderVoMapper;
import com.zhuiYun.project.api.order.mapper.OrdersAfterSalesMapper;
import com.zhuiYun.project.api.order.mapper.OrdersRetreatMapper;
import com.zhuiYun.project.api.order.service.OrderService;
import com.zhuiYun.project.api.seckill.entity.SeckillEntity;
import com.zhuiYun.project.api.seckill.mapper.SeckillMapper;
import com.zhuiYun.project.api.shoppingcart.entity.ShoppingCartEntity;
import com.zhuiYun.project.api.shoppingcart.mapper.ShoppingCartMapper;
import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonConstants;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.util.OrderUtil;
import com.zhuiYun.project.util.PrimaryKeyUtil;
import com.zhuiYun.project.util.RedisUtil;
import com.zhuiYun.project.util.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName OrderServiceImpl
 * @Description TODO 订单后台接口
 * @Author lzy
 * @Date 2023/4/3 10:07
 **/
@Service
public class OrderServiceImpl implements OrderService {

    /**
     * 超时时间，单位为毫秒
     */
    private static final int TIMEOUT = 10 * 1000;

    /**
     * 锁前缀
     */
    private static final String LOCK_PREFIX = "seckill_lock_";

    /**
     * 锁过期时间，单位为毫秒
     */
    private static final int LOCK_EXPIRE = 60 * 1000;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderVoMapper orderVoMapper;

    @Autowired
    OrderService orderService;

    // diy商品mapper
    @Autowired
    HandworkDiyMapper handworkDiyMapper;

    // 商品mapper
    @Autowired
    CommodityMapper commodityMapper;

    // 商品订单mapper
    @Autowired
    CommodityOrderMapper commodityOrderMapper;

    // diy商品订单mapper
    @Autowired
    HandworkDiyOrderMapper handworkDiyOrderMapper;

    // 生成订单号工具类
    @Autowired
    PrimaryKeyUtil primaryKeyUtil;

    // 支付接口类
    @Autowired
    AlipayService alipayService;

    // 抢购接口
    @Autowired
    SeckillMapper seckillMapper;

    @Autowired
    OrdersAfterSalesMapper ordersAfterSalesMapper;

    @Autowired
    OrdersRetreatMapper ordersRetreatMapper;

    // 购物车mapper
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    // 创建lock锁
    ReentrantLock lock = new ReentrantLock();


    /**
        * @Author yuanb
        * @Description 查询所有订单（pc）
        * @Date 2023/4/18 15:52
        * @Return com.zhuiYun.project.common.response.CommonResult
        * @param userId
    */
    public List<OrdersVo> getMyAllOrderPc(Integer userId){
        OrdersVo orderVO = new OrdersVo();
        //查询总订单信息
        List<OrdersVo> allList = orderVoMapper.getMyOrder(userId);
        //遍历商品和diy商品
        for (OrdersVo OrdersVo1 : allList) {
            //查询商品订单信息
            if (OrdersVo1.getOrderTypeId() == 1) {
                CommodityOrderVo commodityOrderVo = new CommodityOrderVo();
                commodityOrderVo.setId(OrdersVo1.getId());
                List<CommodityOrderVo> list = orderVoMapper.getMyCommodityAllOrderpc(commodityOrderVo.getId());
                OrdersVo1.setCommodityOrderList(list);
             //查询diy商品订单信息
            } else if (OrdersVo1.getOrderTypeId() == 2) {
                HandworkDiyOrderVo handworkDiyOrderVo = new HandworkDiyOrderVo();
                handworkDiyOrderVo.setId(OrdersVo1.getId());
                List<HandworkDiyOrderVo> diyList = orderVoMapper.getMyDiyAllOrderpc(handworkDiyOrderVo.getId());
                OrdersVo1.setHandworkDiyOrderList(diyList);
            }
        }
        // 对所有的list进行时间排序
        List<OrdersVo> allList1 = allList.stream().sorted(Comparator.comparing(OrdersVo::getCreateTime).reversed()).collect(Collectors.toList());
        return allList1;
    }

/**
     * @Author yuanb
     * @Description 查询点击状态的订单信息（用于我的订单中订单状态栏pc）
     * @Date 2023/4/18 15:52
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userId
     */
    @Override
    public CommonResult getStatusToOrderPc(Integer status, Integer userId) {
        // 如果订单状态为0时，调用查看所有订单的方法
        if(status ==0){
            List<OrdersVo> orderList = orderService.getMyAllOrderPc(userId);
            return CommonResult.ok(orderList);
        }
        // 不是，则查询别的对应订单的状态
        else{
            List<OrdersVo> list = orderVoMapper.getMyStatusOdersPc(status,userId);
            //遍历商品和diy商品
            for (OrdersVo OrdersVo1 : list) {
                //查询商品订单信息
                if (OrdersVo1.getOrderTypeId() == 1) {
                    CommodityOrderVo commodityOrderVo = new CommodityOrderVo();
                    commodityOrderVo.setId(OrdersVo1.getId());
                    List<CommodityOrderVo> list1 = orderVoMapper.getMyCommodityAllOrderpc(commodityOrderVo.getId());
                    OrdersVo1.setCommodityOrderList(list1);
                    //查询diy商品订单信息
                } else if (OrdersVo1.getOrderTypeId() == 2) {
                    HandworkDiyOrderVo handworkDiyOrderVo = new HandworkDiyOrderVo();
                    handworkDiyOrderVo.setId(OrdersVo1.getId());
                    List<HandworkDiyOrderVo> diyList = orderVoMapper.getMyDiyAllOrderpc(handworkDiyOrderVo.getId());
                    OrdersVo1.setHandworkDiyOrderList(diyList);
                }
            }
            return CommonResult.ok(list);

        }
    }

    /**
     * @Author gpd
     * @Description 查询用户所有的订单信息
     * @Date 2023-04-04 上午 09:17
     * @Return  CommonResult
     * @param userId
     */
    @Override
    public List<OrderVO> getMyAllOrder(Integer userId) {
        //查询总订单信息
        List<OrderVO> myAllOrderList = orderVoMapper.getMyOrders(userId);
        //创建新list集合存放diy和商品 订单信息
        List<OrderVO> list = new ArrayList<>();
        //创建新diyList集合存放diy订单信息
        List<OrderVO> diyList = new ArrayList<>();
        // 便利总订单信息存放diy和商品订单信息
        for (OrderVO orderVO : myAllOrderList){
            //判断商品订单类型
            if(orderVO.getOrderTypeId() == 1 && userId.equals(orderVO.getUserId())){
                //获取商品订单存放到list
                list.addAll(orderVoMapper.getMyCommodityAllOrder(orderVO.getId(),orderVO.getUserId()));
            }
            //判断diy订单类型
            if(orderVO.getOrderTypeId() == 2 && userId.equals(orderVO.getUserId())){
                //获取diy订单存放到list
                diyList.addAll(orderVoMapper.getMyDiyAllOrder(orderVO.getId(),orderVO.getUserId()));
            }
        }
        // 切分商品图片的字符串并拿取第一次id作为商品图片展示
        // 并拼接地址
        for(OrderVO o : list){
            o.setAddress(o.getAddressLocationProvince()+o.getAddressLocationCity()+o.getAddressLocationCounty()+o.getAddressDetailed());
            String[] strArr =o.getImageId().split(",");
            o.setImageId(strArr[0]);
        }
        // 拼接diy商品地址
        for(OrderVO orderVO : diyList){
            orderVO.setAddress(orderVO.getAddressLocationProvince()+orderVO.getAddressLocationCity()+orderVO.getAddressLocationCounty()+orderVO.getAddressDetailed());
        }
        // 将diy商品商品list放进商品的list里
        list.addAll(diyList);
        // 对所有的list进行时间排序
        List<OrderVO> list1 = list.stream().sorted(Comparator.comparing(OrderVO::getCreateTime).reversed()).collect(Collectors.toList());
        return list1;
    }

    /**
     * @Author gpd
     * @Description 搜索查询用户订单信息（用于uniapp我的订单搜索栏）
     * @Date 2023-04-06 下午 08:56
     * @Return CommonResult
     * @param userId
     * @param myOrderValue
     */
    @Override
    public CommonResult getSelectOrderList(String myOrderValue,Integer userId) {
        // 搜索栏长度为19时，为订单号
        if(myOrderValue.length()==19){
            List<OrderVO> list = orderService.getMyAllOrder(userId);
            List<OrderVO >fuzzySearch = new ArrayList();
            String name=myOrderValue;
            Pattern pattern = Pattern.compile(name);
            for(int i=0; i < list.size(); i++){
                //那个属性搜索就get哪个属性
                Matcher matcher = pattern.matcher(((OrderVO)list.get(i)).getOrderNumber());
                //模糊查询用matcher.find()
                if(matcher.find()){
                    fuzzySearch.add(list.get(i));
                }
            }
            return CommonResult.ok(fuzzySearch);
        }
        // 搜索栏为空时，返回全查
        else if(myOrderValue==""){
            List<OrderVO> orderList = orderService.getMyAllOrder(userId);
            return CommonResult.ok(orderList);
        }
        // 搜索栏有值且长度不为19时，则查询商品名称和diy名称
        else{
            List<OrderVO> orderList = orderService.getMyAllOrder(userId);
            List<OrderVO> SelectCommodityNameList = new ArrayList<>();
            String name=myOrderValue;
            Pattern pattern = Pattern.compile(name);
            for(int i=0; i < orderList.size(); i++){
                //那个属性搜索就get哪个属性
                // 如果商品名称为空就去查diy名称
                if(orderList.get(i).getCommodityName()==null){
                    Matcher matcher1 = pattern.matcher(((OrderVO)orderList.get(i)).getDiyName());
                    //模糊查询用matcher.find()
                    if(matcher1.find()){
                        SelectCommodityNameList.add(orderList.get(i));
                    }
                }
                // 否则反之
                else{
                    Matcher matcher = pattern.matcher(((OrderVO)orderList.get(i)).getCommodityName());
                    //模糊查询用matcher.find()
                    if(matcher.find()){
                        SelectCommodityNameList.add(orderList.get(i));
                    }
                }

            }
            return CommonResult.ok(SelectCommodityNameList);
        }
    }

    /**
     * @Author gpd
     * @Description 查询点击状态的订单信息（用于我的订单中订单状态栏）
     * @Date 2023-04-07 上午 09:41
     * @Return CommonResult
     * @param userId
     * @param status
     */
    @Override
    public CommonResult getStatusToOrder(Integer status,Integer userId) {
        // 如果订单状态为0时，调用查看所有订单的方法
        if(status ==0){
            List<OrderVO> orderList = orderService.getMyAllOrder(userId);
            return CommonResult.ok(orderList);
        }
        // 不是，则查询别的对应订单的状态
        else{
            List<OrderVO> list = orderVoMapper.getMyStatusOders(status,userId);
            List<OrderVO> commodityList = new ArrayList<>();
            List<OrderVO> diyList = new ArrayList<>();
            for (OrderVO orderVO : list){
                if(orderVO.getOrderTypeId() == 1){
                    commodityList.addAll(orderVoMapper.getMyStatusCommodityAllOrder(orderVO.getId(),orderVO.getUserId(),status));
                }else{
                    diyList.addAll(orderVoMapper.getMyStatusDiyAllOrder(orderVO.getId(),orderVO.getUserId(),status));
                }
            }
            // 切分商品图片的字符串并拿取第一次id作为商品图片展示
            // 并拼接地址
            for(OrderVO o : commodityList){
                o.setAddress(o.getAddressLocationProvince()+o.getAddressLocationCity()+o.getAddressLocationCounty()+o.getAddressDetailed());
                String[] strArr =o.getImageId().split(",");
                o.setImageId(strArr[0]);
            }
            // 拼接diy商品地址
            for(OrderVO orderVO : diyList){
                orderVO.setAddress(orderVO.getAddressLocationProvince()+orderVO.getAddressLocationCity()+orderVO.getAddressLocationCounty()+orderVO.getAddressDetailed());
            }
            commodityList.addAll(diyList);
            List<OrderVO> list1 = commodityList.stream().sorted(Comparator.comparing(OrderVO::getCreateTime).reversed()).collect(Collectors.toList());
            return CommonResult.ok(list1);

        }
    }

    /**
     * @param userId
     * @Author yuanb
     * @Description 查询用户订单详情信息(用于pc端订单详细详细查询)
     * @Date 2023/4/9 15:57
     * @Return com.zhuiYun.project.common.response.CommonResult
     * * @param userId
     */
    @Override
    public List<OrderVO> getInformation(Integer userId,Integer id) {
        //查询订单信息
        List<OrderVO> informationList = orderVoMapper.getInformation(userId,id);
        //便利informationList
        for (OrderVO orderVO1 : informationList){
            orderVO1.setAddress(orderVO1.getAddressLocationProvince()+orderVO1.getAddressLocationCity()+orderVO1.getAddressLocationCounty()+orderVO1.getAddressDetailed());
            List<OrderVO> list = orderVoMapper.getInformationf(orderVO1.getId());
            orderVO1.setCommodityList(list);
        }
        return informationList;
    }

    /**
     * @param userId
     * @param id
     * @Author yuanb 查询用户订单diy详情信息(用于pc端订单详细详细查询)
     * @Description
     * @Date 2023/4/9 15:57
     * @Return com.zhuiYun.project.common.response.CommonResult
     * * @param userId
     */
    @Override
    public List<OrderVO> getDiyInformation(Integer userId, Integer id) {
        OrderVO orderVO = new OrderVO();
        //查询diy订单信息
        List<OrderVO> informationList = orderVoMapper.getDiyInformation(userId,id);
        for(OrderVO orderVO1 : informationList){
            orderVO1.setAddress(orderVO1.getAddressLocationProvince()+orderVO1.getAddressLocationCity()+orderVO1.getAddressLocationCounty()+orderVO1.getAddressDetailed());
            List<OrderVO> orderVOList = orderVoMapper.getDiyInformationf(orderVO1.getId());
            orderVO1.setDiyOrderList(orderVOList);
        }
        return informationList;
    }

    /**
     * @param userId
     * @param id
     * @Author yuanb 查询用户订单步骤详情信息(用于pc端订单详细详细查询)
     * @Description
     * @Date 2023/4/9 15:57
     * @Return com.zhuiYun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getStepList(Integer userId, Integer id) {
        OrderVO StepList = orderVoMapper.getStepList(userId,id);
        return CommonResult.ok(StepList);
    }

    /**
     * @param userId
     * @Author yuanb
     * @Description 获取售后列表(pc端)
     * @Date 2023/4/11 16:40
     * @Return com.zhuiYun.project.common.response.CommonResult
     * * @param userId
     */
    @Override
    public CommonResult getAfterSalesList(Integer userId) {
        //查询全部售后信息
        List<OrderVO> afterSalesList = orderVoMapper.getMyAllOrderAfterSales(userId);
        List<OrderVO> list = new ArrayList<>();
        List<OrderVO> diyList = new ArrayList<>();
        // 便利afterSalesList
        for (OrderVO orderVO : afterSalesList){
            if(orderVO.getOrderTypeId() == 1 && userId.equals(orderVO.getUserId())){
                list.addAll(orderVoMapper.getMyCommodityOrderAfterSales(orderVO.getUserId(),orderVO.getStatusId()));
            }
            if(orderVO.getOrderTypeId() == 2 && userId.equals(orderVO.getUserId())  && orderVO.getStatusId()>=2){
                diyList.addAll(orderVoMapper.getMyDiyOrderAfterSales(orderVO.getUserId()));
            }
        }
        // 将diy商品商品list放进商品的list里
        list.addAll(diyList);
        return CommonResult.ok(list);
    }

    /**
     * @param OrdersAfterSales
     * @Author yuanb
     * @Description 添加售后列表(pc端)
     * @Date 2023/4/11 16:38
     * @Return com.zhuiYun.project.common.response.CommonResult
     * * @param orderVO
     */
    @Override
    public CommonResult AfterSalesList(OrdersAfterSales OrdersAfterSales,MultipartFile file) {
        if(OrdersAfterSales != null){
            // 上传图片
            if (file != null) {
                String id = UploadFileUtils.uploadFile(file);
                OrdersAfterSales.setImageId(id);
            }
            // 添加售后中间表
            OrdersRetreat ordersRetreat = new OrdersRetreat();
            // 删除标识
            ordersRetreat.setDelFlag(0);
            // 申请售后记录
            ordersRetreat.setOrdersRetreatTakeNotes(1);
            // 用户id
            ordersRetreat.setUserId(OrdersAfterSales.getUserId());
            // 订单id
            ordersRetreat.setOrdersId(OrdersAfterSales.getEId());
            // 商品售后信息id
            ordersRetreat.setOrdersAfterSalesId(OrdersAfterSales.getId());
            //售后类型
            ordersRetreat.setOrdersStatusId(OrdersAfterSales.getOrdersType());
            // 创建时间
            ordersRetreat.setCreateTime(new Date());
            ordersRetreatMapper.insertSelective(ordersRetreat);
            // 添加售后信息表
            OrdersAfterSales.setDelFlag(0);
            int i = ordersAfterSalesMapper.AfterSalesList(OrdersAfterSales);
            return CommonResult.ok(i);
        }else {
            return CommonResult.error(EmErrorCode.SAVE_ERROR);
        }

    }

    /**
        * @Author yuanb
        * @Description 修改售后列表信息(pc端)
        * @Date 2023/4/15 9:32
        * @Return com.zhuiYun.project.common.response.CommonResult
        * * @param ordersRetreat
    */
    @Override
    public CommonResult updateOrder(Integer id) {
        if(id != null){
            int i = ordersRetreatMapper.updateOrder(id);
            return CommonResult.ok(i);
        }else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
        * @Author yuanb
        * @Description 查询订单支付状态
        * @Date 2023/4/16 19:13
        * @Return com.zhuiYun.project.common.response.CommonResult
        * * @param id
    */
    @Override
    public CommonResult getId(Integer id) {
        int i = orderVoMapper.getId(id);
        return CommonResult.ok(i);
    }



    /**
    * @Description 取消diy订单
    * @Author lzy
    * @Date 2023/4/17 19:06
    * @Return com.zhuiYun.project.common.response.CommonResult
    * @param orderId
    */
    @Override
    @Transactional
    public CommonResult cancelDiyOrder(Integer orderId) {
        Order order = new Order();
        order.setId(orderId);
        order = orderMapper.selectOne(order);
        int delete = orderMapper.delete(order);
        if (delete > 0) {
            HandworkDiyOrder handworkDiyOrder = new HandworkDiyOrder();
            handworkDiyOrder.setOrdersId(orderId);
            List<HandworkDiyOrder> handworkDiyOrders = handworkDiyOrderMapper.select(handworkDiyOrder);
            for (HandworkDiyOrder diyOrder : handworkDiyOrders) {
                // 回滚diy订单库存
                Integer i = handworkDiyMapper.rollBackInventory(diyOrder.getDiyId(), diyOrder.getHandworkDiyQuantity());
                if (i > 0) {
                    // 删除订单记录
                    int delete1 = handworkDiyOrderMapper.delete(diyOrder);
                    if(delete1 <= 0){
                        //手动强制回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                    }
                } else {
                    //手动强制回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                }
            }
        } else {
            //手动强制回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
        }
        RedisUtil.del(CommonConstants.DIY_ORDER + order.getOrderNumber());
        return CommonResult.ok("取消成功");
    }
    /**
     * @Description 商品订单过期未支付，执行订单回滚操作
     * @Author lzy
     * @Date 2023/4/12 16:30
     * @Return void
     * @param orderNumber
     */
    @Override
    public CommonResult commodityOrderRollBack(String orderNumber) throws CommonException {
        try {
            lock.lock();
            Order order = new Order();
            order.setOrderNumber(orderNumber);
            Order order1 = orderMapper.selectOne(order);
            // orderTypeId为1的是商品订单
            if (order1.getOrderTypeId() == 1) {
                CommodityOrder commodityOrder = new CommodityOrder();
                commodityOrder.setOrdersId(order1.getId());
                List<CommodityOrder> commodityOrderList = commodityOrderMapper.select(commodityOrder);
                for (CommodityOrder commodityOrderTwo : commodityOrderList) {
                    SeckillEntity seckillEntity = seckillMapper.selectInventory(commodityOrderTwo.getCommodityId());
                    Integer integer;//手动强制回滚事务
                    if (seckillEntity != null) {
                        // 秒杀表回滚库存
                        integer = seckillMapper.rollBackInventory(commodityOrderTwo.getCommodityId(), commodityOrderTwo.getCommodityQuantity());
                        if (redisTemplate.hasKey(CommonConstants.COMMODITY_SECKILL_STOCK + commodityOrderTwo.getCommodityId())){
                            redisTemplate.opsForValue().increment(CommonConstants.COMMODITY_SECKILL_STOCK+commodityOrderTwo.getCommodityId());
                        }
                    } else {
                        // 回滚商品库存
                        integer = commodityMapper.rollBackInventory(commodityOrderTwo.getCommodityId(), commodityOrderTwo.getCommodityQuantity());
                        if (redisTemplate.hasKey(CommonConstants.COMMODITY_STOCK + commodityOrderTwo.getCommodityId())){
                            redisTemplate.opsForValue().increment(CommonConstants.COMMODITY_STOCK+commodityOrderTwo.getCommodityId());
                        }
                    }
                    // 删除商品订单记录
                    int integerTwo = commodityOrderMapper.delete(commodityOrderTwo);
                    if (integer <= 0 && integerTwo <= 0) {
                        //手动强制回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                    }
                }
            } else {
                //手动强制回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
            // 根据订单编号删除订单
            Integer ordersDeleteFlag = orderMapper.deleteByOrderNumber(orderNumber);
            if (ordersDeleteFlag <= 0) {
                //手动强制回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
        } finally {
            lock.unlock();
        }
        return CommonResult.ok("取消成功");
    }

    /**
     *
     * @author: HKY
     * @date: 2023/4/24 15:06
     * @param orderId
     * @return com.zhuiYun.project.common.response.CommonResult
     * @Description:  取消商品订单
     */
    @Override
    public CommonResult cancelCommodityOrder(Integer orderId) throws CommonException {
        Order order = new Order();
        order.setId(orderId);
        order = orderMapper.selectOne(order);
        int delete = orderMapper.delete(order);
        if (delete > 0) {
            CommodityOrder commodityOrder = new CommodityOrder();
            commodityOrder.setOrdersId(orderId);
            List<CommodityOrder> commodityOrderList = commodityOrderMapper.select(commodityOrder);
            for (CommodityOrder commodityOrderTwo : commodityOrderList) {
                SeckillEntity seckillEntity = seckillMapper.selectInventory(commodityOrderTwo.getCommodityId());
                Integer integer;//手动强制回滚事务
                if (seckillEntity != null) {
                    // 秒杀表回滚库存
                    integer = seckillMapper.rollBackInventory(commodityOrderTwo.getCommodityId(), commodityOrderTwo.getCommodityQuantity());
                    if (redisTemplate.hasKey(CommonConstants.COMMODITY_SECKILL_STOCK + commodityOrderTwo.getCommodityId())){
                        redisTemplate.opsForValue().increment(CommonConstants.COMMODITY_SECKILL_STOCK+commodityOrderTwo.getCommodityId());
                    }
                } else {
                    // 回滚商品库存
                    integer = commodityMapper.rollBackInventory(commodityOrderTwo.getCommodityId(), commodityOrderTwo.getCommodityQuantity());
                    if (redisTemplate.hasKey(CommonConstants.COMMODITY_STOCK + commodityOrderTwo.getCommodityId())){
                        redisTemplate.opsForValue().increment(CommonConstants.COMMODITY_STOCK+commodityOrderTwo.getCommodityId());
                    }
                }
                // 删除商品订单记录
                int integerTwo = commodityOrderMapper.delete(commodityOrderTwo);
                if (integer <= 0 && integerTwo <= 0) {
                    //手动强制回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                }
            }
        } else {
            //手动强制回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
        }
        RedisUtil.del(CommonConstants.ORDER + order.getOrderNumber());
        return CommonResult.ok("取消成功");
    }

    /**
     * @Description 询问当前订单状态
     * @Author lzy
     * @Date 2023/4/12 15:53
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param alipayEntity
     */
    @Override
    public CommonResult getDiyOrderQuery(AlipayEntity alipayEntity) throws CommonException, AlipayApiException {
        if (alipayEntity.getOrderTypeId() == 2) {
            Object o = RedisUtil.get(CommonConstants.DIY_ORDER + alipayEntity.getOrderNumber());
            if (o != null) {
                Map<String, Object> query = alipayService.query(alipayEntity.getOutTradeNo());
                if (query.get("tradeStatus") != null && query.get("tradeStatus").equals("TRADE_SUCCESS")) {
                    RedisUtil.del(CommonConstants.DIY_ORDER + alipayEntity.getOrderNumber());
                    // 支付成功修改订单状态 以及添加支付时间
                    orderMapper.updateOrderStatus(alipayEntity.getOrderNumber());
                }
                return CommonResult.ok(query);
            } else {
                return CommonResult.error(EmErrorCode.ORDER_EXPIRATION);
            }
        } else if(alipayEntity.getOrderTypeId() == 1) {
            Object o = RedisUtil.get(CommonConstants.ORDER + alipayEntity.getOrderNumber());
            if (o != null) {
                Map<String, Object> query = alipayService.query(alipayEntity.getOutTradeNo());
                if (query.get("tradeStatus") != null && query.get("tradeStatus").equals("TRADE_SUCCESS")) {
                    RedisUtil.del(CommonConstants.ORDER + alipayEntity.getOrderNumber());
                    // 支付成功修改订单状态 以及添加支付时间
                    orderMapper.updateOrderStatus(alipayEntity.getOrderNumber());
                }
                return CommonResult.ok(query);
            } else {
                return CommonResult.error(EmErrorCode.ORDER_EXPIRATION);
            }
        }
        return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
    }

    /**
     * @Description 订单过期未支付，执行订单回滚操作
     * @Author lzy
     * @Date 2023/4/12 16:31
     * @Return void
     * @param orderNumber
     */
    @Override
    @Transactional
    public CommonResult diyOrderRollBack(String orderNumber) throws CommonException {
        try {
            lock.lock();
            Order order = new Order();
            order.setOrderNumber(orderNumber);
            Order order1 = orderMapper.selectOne(order);
            // orderTypeId为2的是diy订单
            if (order1.getOrderTypeId() == 2) {
                HandworkDiyOrder handworkDiyOrder = new HandworkDiyOrder();
                handworkDiyOrder.setOrdersId(order1.getId());
                List<HandworkDiyOrder> handworkDiyOrders = handworkDiyOrderMapper.select(handworkDiyOrder);
                for (HandworkDiyOrder diyOrder : handworkDiyOrders) {
                    // 回滚diy订单库存
                    Integer i = handworkDiyMapper.rollBackInventory(diyOrder.getDiyId(), diyOrder.getHandworkDiyQuantity());
                    if (i > 0) {
                        // 删除订单记录
                        int delete = handworkDiyOrderMapper.delete(diyOrder);
                        if(delete <= 0){
                            //手动强制回滚事务
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                        }
                    } else {
                        //手动强制回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                    }
                }
            } else {
                //手动强制回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
            // 根据订单编号删除订单
            Integer ordersDeleteFlag = orderMapper.deleteByOrderNumber(orderNumber);
            if (ordersDeleteFlag <= 0) {
                //手动强制回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
        } finally {
            lock.unlock();
        }
        return CommonResult.ok("取消成功");
    }

    /**
     * @Description 用户提交订单
     * @Author lzy
     * @Date 2023/4/7 9:38
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param submitOrderVo
     */
    @Override
    @Transactional
    public CommonResult submitCommodityOrder(SubmitOrderVo submitOrderVo) throws CommonException {
        // 存放order总订单订单号
        ArrayList<SubmitOrderReturn> orderNumberList = new ArrayList<>();
        List<CommodityArr> commodityArrs = JSON.parseArray(submitOrderVo.getProductArr(), CommodityArr.class);
        // 判断是否有商品
        if (!commodityArrs.isEmpty()){
            // 生成26位订单编号
            String orderNumber = OrderUtil.getOrderCode(submitOrderVo.getUserId());
            // 生成18位订单支付单号（第三方支付流水号）
            String outTradeNo = primaryKeyUtil.getOrderId();
            // 判断订单支付单号生成是否成功
            if (outTradeNo.isEmpty()) {
                //手动强制回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
            // 计算总价格
            BigDecimal commodityTotalPrice = new BigDecimal(0);
            for (CommodityArr commodityArr : commodityArrs) {
                commodityTotalPrice = commodityTotalPrice.add(commodityArr.getTotalPrice());
            }
            Order order = new Order();
            // 订单编号
            order.setOrderNumber(orderNumber);
            // 存放订单支付单号（第三方支付流水号）
            order.setOutTradeNo(outTradeNo);
            // 商品总金额
            order.setCommodityAmountTotal(commodityTotalPrice);
            // 订单总金额
            order.setOrderAmountTotal(commodityTotalPrice);
            // 运费
            order.setFreight(submitOrderVo.getFreight());
            // 收货地址id
            order.setAddressId(submitOrderVo.getAddressId());
            // 购买人id
            order.setUserId(submitOrderVo.getUserId());
            // 支付方式
            order.setPayModeId(submitOrderVo.getPayModeId());
            // 订单状态
            order.setStatusId(1);
            // 订单类型
            order.setOrderTypeId(1);
            Date nowDate = new Date();
            // 订单过期时间
            order.setExpirationTime(new Date(nowDate.getTime() + 600000));
            // 创建时间
            order.setCreateTime(new Date());
            // 删除标识
            order.setDelFlag(0);
            // 生成订单
            int insert = orderMapper.insert(order);
            Commodity commodityEntity = new Commodity();
            Example example = new Example(ShoppingCartEntity.class);
            Example.Criteria criteria = example.createCriteria();
            for (CommodityArr commodity : commodityArrs) {
                // 查询是否是秒杀商品
                SeckillEntity seckillEntity = seckillMapper.selectInventory(commodity.getId());
                commodityEntity.setId(commodity.getId());
                Commodity commodity1 = commodityMapper.selectOne(commodityEntity);
                CommodityOrder commodityOrder = new CommodityOrder();
                if (seckillEntity == null) {
                    // 判断商品库存是否足够
                    if (commodity1.getGoodsQuantity() >= commodity.getNumber()) {
                        // 减商品库存
                        Integer reduceInventoryFlag = commodityMapper.reduceInventory(commodity.getId(), commodity.getNumber());
                        if (reduceInventoryFlag > 0) {
                            // 商品id
                            commodityOrder.setCommodityId(commodity1.getId());
                            // 商品下单的数量
                            commodityOrder.setCommodityQuantity(commodity.getNumber());
                            // 总订单id
                            commodityOrder.setOrdersId(order.getId());
                            // 商品下单时价格
                            commodityOrder.setCommodityPrice(commodity1.getFavorablePrice());
                            // 创建时间
                            commodityOrder.setCreateTime(new Date());
                            // 删除标识
                            commodityOrder.setDelFlag(0);
                            int i = commodityOrderMapper.insert(commodityOrder);
                            if (i == 0) {
                                //手动强制回滚事务
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                            }
                        } else {
                            //手动强制回滚事务
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                        }
                    } else {
                        //手动强制回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return CommonResult.error(40002, "对不起，您选择的" + commodity1.getCommodityName() + "商品库存数量仅剩" + commodity1.getGoodsQuantity());
                    }
                } else {
                    if (seckillEntity.getDelFlag() == 0 & seckillEntity.getDelFlag().equals(0)) {
                        // 判断商品库存是否足够
                        if (seckillEntity.getSeckillStock() >= commodity.getNumber()) {
                            // 减商品库存
                            Integer reduceInventoryFlag = seckillMapper.reduceInventory(commodity.getId(), commodity.getNumber());
                            if (reduceInventoryFlag > 0) {
                                // 商品id
                                commodityOrder.setCommodityId(commodity1.getId());
                                // 商品下单的数量
                                commodityOrder.setCommodityQuantity(commodity.getNumber());
                                // 总订单id
                                commodityOrder.setOrdersId(order.getId());
                                // 商品下单时价格
                                commodityOrder.setCommodityPrice(commodity1.getFavorablePrice());
                                // 创建时间
                                commodityOrder.setCreateTime(new Date());
                                // 删除标识
                                commodityOrder.setDelFlag(0);
                                int i = commodityOrderMapper.insert(commodityOrder);
                                if (i == 0) {
                                    //手动强制回滚事务
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                                }
                            } else {
                                //手动强制回滚事务
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                            }
                        } else {
                            //手动强制回滚事务
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return CommonResult.error(40002, "对不起，您选择的" + commodity1.getCommodityName() + "商品秒杀库存数量仅剩" + seckillEntity.getSeckillStock());
                        }
                    } else {
                        //手动强制回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return CommonResult.error(40002, "对不起，您选择的秒杀商品" + commodity1.getCommodityName() + "已结束");
                    }
                }
                criteria.orEqualTo("commodityId", commodity.getId());
            }
            criteria.andEqualTo("isNoDiy", 0);
            shoppingCartMapper.deleteByExample(example);
            RedisUtil.set(CommonConstants.ORDER + orderNumber, order,600);
            SubmitOrderReturn submitOrderReturn = new SubmitOrderReturn();
            submitOrderReturn.setPrice(order.getOrderAmountTotal());
            submitOrderReturn.setOutTradeNo(order.getOutTradeNo());
            submitOrderReturn.setOrderNumber(order.getOrderNumber());
            // 订单备注
            submitOrderReturn.setSubjectName("商品订单");
            // 订单类型
            submitOrderReturn.setOrderTypeId(order.getOrderTypeId());
            orderNumberList.add(submitOrderReturn);
        }
        return CommonResult.ok(orderNumberList);
    }


    /**
     * @Description 提交diy商品订单
     * @Author lzy
     * @Date 2023/4/19 11:25
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param submitOrderVo
     */
    @Override
    @Transactional
    public CommonResult submitHandDiyOrder(SubmitOrderVo submitOrderVo) {
        // 获取分布式锁
        String lockKey = LOCK_PREFIX + submitOrderVo.getUserId();
        String lockValue = UUID.randomUUID().toString();
        boolean locked = false;
        try{
            // 设置成功并返回true,否则设置失败并返回false
            locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, LOCK_EXPIRE, TimeUnit.MILLISECONDS);
            if(!locked) {
                return CommonResult.error(500,"网络繁忙请稍后再试！");
            }
            // 存放order总订单订单号
            ArrayList<SubmitOrderReturn> orderNumberList = new ArrayList<>();
            List<DiyArr> diyArrs = JSON.parseArray(submitOrderVo.getProductArr(), DiyArr.class);
            if (!diyArrs.isEmpty()){
                HandworkDiy handworkDiy = new HandworkDiy();
                Example example = new Example(ShoppingCartEntity.class);
                Example.Criteria criteria = example.createCriteria();
                // 计算diy商品总价格
                BigDecimal diyTotalPrice = new BigDecimal(0);
                for (DiyArr diyArr : diyArrs) {
                    diyTotalPrice = diyTotalPrice.add(diyArr.getTotalPrice());
                }
                // 创建订单
                // 生成26位订单编号
                String orderNumber = OrderUtil.getOrderCode(submitOrderVo.getUserId());
                // 生成18位订单支付单号（第三方支付流水号）
                String outTradeNo = primaryKeyUtil.getOrderId();
                // 判断订单支付单号生成是否成功
                if (outTradeNo.isEmpty()) {
                    //手动强制回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                }
                Order order = new Order();
                // 存放订单编号
                order.setOrderNumber(orderNumber);
                // 存放订单支付单号（第三方支付流水号）
                order.setOutTradeNo(outTradeNo);
                // 商品总金额
                order.setCommodityAmountTotal(diyTotalPrice);
                // 订单总金额
                order.setOrderAmountTotal(submitOrderVo.getOrderAmountTotal());
                // 运费
                order.setFreight(submitOrderVo.getFreight());
                // 收货地址id
                order.setAddressId(submitOrderVo.getAddressId());
                // 购买人id
                order.setUserId(submitOrderVo.getUserId());
                // 支付方式
                order.setPayModeId(submitOrderVo.getPayModeId());
                // 订单状态
                order.setStatusId(1);
                // 订单类型
                order.setOrderTypeId(2);
                Date nowDate = new Date();
                // 订单过期时间
                order.setExpirationTime(new Date(nowDate.getTime() + 600000));
                // 创建时间
                order.setCreateTime(new Date());
                // 删除标识
                order.setDelFlag(0);
                int insert = orderMapper.insert(order);
                if (insert > 0) {
                    for (DiyArr diyArr : diyArrs) {
                        handworkDiy.setId(diyArr.getId());
                        HandworkDiy handworkDiy1 = handworkDiyMapper.selectOne(handworkDiy);
                        HandworkDiyOrder handworkDiyOrder = new HandworkDiyOrder();
                        // 判断diy商品库存是否足够
                        if (handworkDiy1.getDiyNumber() >= diyArr.getNumber()) {
                            // 减diy商品库存
                            Integer reduceInventoryFlag = handworkDiyMapper.reduceInventory(diyArr.getId(), diyArr.getNumber());
                            if (reduceInventoryFlag > 0) {
                                // diy商品的id
                                handworkDiyOrder.setDiyId(diyArr.getId());
                                // diy商品下单时的价格
                                handworkDiyOrder.setDiyPrice(handworkDiy1.getDiyFavorablePrice());
                                // diy总订单id
                                handworkDiyOrder.setOrdersId(order.getId());
                                // 创建时间
                                handworkDiyOrder.setCreateTime(new Date());
                                // 创建时间
                                handworkDiyOrder.setHandworkDiyQuantity(diyArr.getNumber());
                                // 到点人数
                                handworkDiyOrder.setArrivalNum(diyArr.getArrivalNum());
                                // 到店时间
                                handworkDiyOrder.setArrivalTime(diyArr.getArrivalTime());
                                // 删除标识
                                handworkDiyOrder.setDelFlag(0);
                                int i = handworkDiyOrderMapper.insert(handworkDiyOrder);
                                if (i == 0) {
                                    //手动强制回滚事务
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                                }
                            } else {
                                //手动强制回滚事务
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                            }
                        } else {
                            //手动强制回滚事务
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return CommonResult.error(40002, "对不起，您选择的" + handworkDiy1.getDiyName() + "diy商品库存数量仅剩" + handworkDiy1.getDiyNumber());
                        }
                        criteria.orEqualTo("commodityId", diyArr.getId());
                    }
                    criteria.andEqualTo("isNoDiy", 1);
                    shoppingCartMapper.deleteByExample(example);
                    RedisUtil.set(CommonConstants.DIY_ORDER + order.getOrderNumber(), order ,600);
                    // 判断支付方式 根据支付方式设置返回参数
                    if (submitOrderVo.getPayModeId() == 1) {
                        SubmitOrderReturn submitOrderReturn = new SubmitOrderReturn();
                        // 订单总金额
                        submitOrderReturn.setPrice(order.getOrderAmountTotal());
                        // 订单支付编号
                        submitOrderReturn.setOutTradeNo(order.getOutTradeNo());
                        // 订单编号
                        submitOrderReturn.setOrderNumber(order.getOrderNumber());
                        // 订单类型
                        submitOrderReturn.setOrderTypeId(order.getOrderTypeId());
                        // 订单备注
                        submitOrderReturn.setSubjectName("手工diy");
                        orderNumberList.add(submitOrderReturn);
                    }
                } else {
                    //手动强制回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
                }
            } else {
                return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
            }
            return CommonResult.ok(orderNumberList);
        } finally {
            // 释放分布式锁
            if(locked){
                redisTemplate.delete(lockKey);
            }
        }
    }

    /**
    * @Description 创建订单
    * @Author lzy
    * @Date 2023/4/19 11:36
    * @Return com.zhuiYun.project.common.response.CommonResult
    * @param submitOrderVo
    */
    public CommonResult createOrder(SubmitOrderVo submitOrderVo, BigDecimal totalPrice){
        // 生成26位订单编号
        String orderNumber = OrderUtil.getOrderCode(submitOrderVo.getUserId());
        // 生成18位订单支付单号（第三方支付流水号）
        String outTradeNo = primaryKeyUtil.getOrderId();
        // 判断订单支付单号生成是否成功
        if (outTradeNo.isEmpty()) {
            //手动强制回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonResult.error(EmErrorCode.ORDER_EXPIRE);
        }
        Order order = new Order();
        // 存放订单编号
        order.setOrderNumber(orderNumber);
        // 存放订单支付单号（第三方支付流水号）
        order.setOutTradeNo(outTradeNo);
        // 商品总金额
        order.setCommodityAmountTotal(totalPrice);
        // 订单总金额
        order.setOrderAmountTotal(submitOrderVo.getOrderAmountTotal());
        // 运费
        order.setFreight(submitOrderVo.getFreight());
        // 收货地址id
        order.setAddressId(submitOrderVo.getAddressId());
        // 购买人id
        order.setUserId(submitOrderVo.getUserId());
        // 支付方式
        order.setPayModeId(submitOrderVo.getPayModeId());
        // 订单状态
        order.setStatusId(1);
        // 订单类型
        order.setOrderTypeId(2);
        Date nowDate = new Date();
        // 订单过期时间
        order.setExpirationTime(new Date(nowDate.getTime() + 600000));
        // 创建时间
        order.setCreateTime(new Date());
        // 删除标识
        order.setDelFlag(0);
        int insert = orderMapper.insert(order);
        return CommonResult.ok(order);
    }
}
